import subprocess
import time


def check_nginx_status():
    try:
        result = subprocess.run(['systemctl', 'is-active', 'nginx'], capture_output=True, text=True)
        if result.stdout.strip() == 'active':
            return True
        else:
            return False
    except Exception as e:
        print(f"Error checking Nginx status: {e}")
        return False


def restart_nginx():
    try:
        subprocess.run(['sudo', 'systemctl', 'restart', 'nginx'], check=True)
        print("Nginx restarted successfully.")
    except subprocess.CalledProcessError as e:
        print(f"Failed to restart Nginx: {e}")


def monitor_and_restart_nginx(interval=60):
    while True:
        if not check_nginx_status():
            print("Nginx is not running. Attempting to restart...")
            restart_nginx()
        else:
            print("Nginx is running.")
        time.sleep(interval)


if __name__ == "__main__":
    monitor_and_restart_nginx()
